package com.atguigu.gmall.activity.controller;


import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {

    @Autowired
    ActivityService activityService;

    @Autowired
    RabbitService rabbitService;

    @Autowired
    RedisTemplate redisTemplate;

    public static final String slat = "Medusa";

    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);

        SeckillGoods seckillGoods = activityService.findBySkuId(skuId);
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Date nowDate = Calendar.getInstance().getTime();
        //判断时间发送抢购码
        if (DateUtil.dateCompare(startTime,nowDate) && DateUtil.dateCompare(nowDate,endTime)){
            String encrypt = MD5.encrypt(slat + userId);
            return Result.ok(encrypt);
        }else {
            return Result.fail().message("不在活动时间内");
        }
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
        //检验抢购码
        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(slat + userId);
        if (!encrypt.equals(skuIdStr) ){
            return Result.fail().message("请重试");
        }
        //检验状态位
        Object seckillpush = CacheHelper.get(skuId.toString());
        if (!seckillpush.equals("1")){
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }
        //发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,userRecode);

        return Result.ok();
    }


    //再次检查
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //5检查用户是否下单
        String userId = AuthContextHolder.getUserId(request);
        Object o5 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if (o5 != null){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
        //4抢购资格
        Object o4 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if (o4 != null){
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
        }
        //3用户是否来过
        Object o3 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId);
        if (o3 == null){
            //3.1用户还没来，此时在状态位
            Object o31 = CacheHelper.get(skuId.toString());
            if (o31.equals("1")){
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);
            }
        }
        //3.1用户来过了，没抢上
        return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
    }

}
